package com.sweet.web.verticle;

import com.sweet.web.ApiHandler;
import com.sweet.web.RouterVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.MySQLClient;
import io.vertx.ext.sql.SQLClient;

import java.util.Arrays;

public class BookVerticle extends AbstractVerticle implements RouterVerticle {

  private SQLClient sqlClient;

  @Override
  public void start() throws Exception {
    super.start();
    JsonObject mysqlConfig = new JsonObject().put("host", "127.0.0.1")
        .put("port", 3306).put("maxPollSize", 10)
        .put("username", "root").put("password", "main")
        .put("database", "vertx");

    sqlClient = MySQLClient.createShared(vertx, mysqlConfig);
    routers.addAll(Arrays.asList(
        new ApiHandler(HttpMethod.GET, "/b1", res -> {
          sqlClient.query("select * from user", r -> {
            if (r.succeeded()) {
              res.response().end(r.result().getRows().toString());
            } else {
              res.response().end(r.cause().getMessage());
            }
          });
        }),
        new ApiHandler(HttpMethod.GET, "/b2", res -> {
          System.out.println(vertx.toString());
          res.response().end("b2 ok");
        })
    ));
  }

}
